import React, { useState, useEffect, useRef } from 'react'
import store from '../../../redux/store'
import { _getUserManageList, _patchUser, _deleteUser, _appendUser, _editUser } from '../../../api/user'
import { _getRoleList } from '../../../api/role'
import { Table, Switch, Modal, Button, notification } from 'antd'
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons';
import UserForm from '../../../components/user-manage/UserForm'
const { confirm } = Modal

export default function UserMange () {

  const [dataSource, setDataSource] = useState([])
  const [isModalVisible, setModalVisible] = useState(false)
  const [roleList, setRoleList] = useState([])
  const [currentFormLine, setCurrentFormLine] = useState({})
  const [title, setTitle] = useState('添加')
  const addForm = useRef(null)

  const columns = [
    {
      title: '部门',
      align: 'center',
      dataIndex: 'region',
      render: (region) => {
        return <b>{region === "" ? '一级部门' : region}</b>
      }
    },
    {
      title: '账号',
      align: 'center',
      dataIndex: 'useraccount',
    },
    {
      title: '用户名称',
      align: 'center',
      dataIndex: 'username',
    },
    {
      title: '角色',
      align: 'center',
      dataIndex: 'role',
      render: (role) => role.roleName
    },
    {
      title: '用户状态',
      align: 'center',
      dataIndex: 'roleState',
      render: (roleState, item) => {
        return <Switch disabled={item.default ? true : false} onChange={() => { changeRoleState(item) }} checked={roleState}></Switch>
      }
    },
    {
      title: '操作',
      align: 'center',
      render: (item) => {
        return <div className="func">
          <Button disabled={item.default ? true : false} type="primary" danger shape="circle" icon={<DeleteOutlined />} onClick={() => { deleteUserOnce(item) }} />
          <Button disabled={item.default ? true : false} type="primary" shape="circle" icon={<EditOutlined />} onClick={() => { openEditUserInfo(item) }} />
        </div>
      }
    }
  ]
  const changeRoleState = (item) => {
    item.roleState = !item.roleState
    let query = {
      id: item.id,
      data: { roleState: item.roleState }
    }
    _patchUser(query).then(res => {
      setDataSource([...dataSource])
    })
  }
  const deleteUserOnce = (item) => {
    confirm({
      title: '删除用户',
      icon: <ExclamationCircleOutlined />,
      content: '此操作将永久删除当前用户，请确认后执行操作',
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      onOk () {
        _deleteUser(item.id).then(res => {
          setDataSource(dataSource.filter((ele) => { return ele.id !== item.id }))
          notification.success({
            message: '删除成功',
            description:
              '当前角色已经从系统中永久删除',
          });
        })
      },
      onCancel () {
        console.log('取消删除操作');
      },
    })
  }
  const openAppendUser = () => {
    setTitle('添加用户')
    setModalVisible(true)
  }
  const openEditUserInfo = (item) => {
    setTimeout(() => {
      setCurrentFormLine(item)
      setTitle('更新用户')
      setModalVisible(true)
    }, 0);

  }
  const addUser = (value) => {
    let data = {
      ...value,
      roleState: true,
      default: false,
    }
    _appendUser(data).then(res => {
      res.role = roleList.filter(item => item.id === res.roleId)[0]
      setDataSource([res, ...dataSource])
      // 清空表单
      addForm.current.resetFields()
      setModalVisible(false)
      notification.success({
        message: '用户添加成功',
        description: '用户已被添加',
      });
    })
  }
  const editUser = (value) => {
    let query = {
      id: currentFormLine.id,
      data: {
        ...value,
        roleState: currentFormLine.roleState,
        default: false
      }
    }
    _editUser(query).then(res => {

      setDataSource(
        dataSource.map((item) => {
          if (item.id === query.id) {
            return {
              ...item,
              ...value,
              role: roleList.filter(data => data.id === value.roleId)[0]
            }
          }
          return item
        })
      )
      notification.success({
        message: '用户更新成功',
        description: '当前用户信息已修改成功',
      });
      setModalVisible(false)
    })

  }
  const handleOk = () => {
    // 校验form表单
    addForm.current.validateFields().then(value => {
      if (title === '添加用户') {
        addUser(value)
        return
      }
      // 修改用户
      editUser(value)
    }).catch((err) => {
      alert('必填内容缺少，请完善内容')
    })
  }
  const handleCancel = () => {
    setModalVisible(false)
  }
  useEffect(() => {
    let userInfo = store.getState().userInfo[0]
    _getUserManageList().then(res => {
      setDataSource(res.filter(item => item.roleId >= userInfo.roleId))
    })
  }, [])
  useEffect(() => {
    _getRoleList().then(res => {
      setRoleList(res)
    })
  }, [])
  return (
    <div>
      <Button type='primary' icon={<PlusOutlined />} onClick={() => { openAppendUser() }}>添加用户</Button>
      <Table dataSource={dataSource} columns={columns} rowKey={item => item.id} scroll={{ y: 700, x: 600 }} pagination={{ pageSize: 10 }}></Table>
      <Modal title={title} visible={isModalVisible} onOk={handleOk} onCancel={handleCancel} cancelText="取消" okText={title === '添加用户' ? '确认' : '更新'} destroyOnClose={true}>
        <UserForm ref={addForm} type={title} currentFormLine={currentFormLine} />
      </Modal>
    </div>
  )
}
